#include "threadPool.h"
int exitPipe[2];
void sigFunc(int signum){
    printf("parent is going to exit!\n");
    write(exitPipe[1],"1",1);
}
int main(int argc, char *argv[])
{
    system("clear");
    // ./main server.conf
    ARGS_CHECK(argc,2);
    FILE* sourfp = fopen(argv[1], "rb");
    ERROR_CHECK(sourfp, NULL, "fopen");
    char ip[256] = {0};
    char port[6] = {0};
    int workerNum = 0;

    fscanf(sourfp, "IP: %s\n", ip);
    fscanf(sourfp, "PORT: %s\n", port);
    fscanf(sourfp, "WORKERNUM: %d", &workerNum);

    printf("ip:%s, port:%s, workernum:%d\n", ip, port, workerNum);

    pipe(exitPipe);         // 子进程退出的标识
    if(fork() != 0){        // 主进程注册10号（自定义信号）信号
        close(exitPipe[0]);
        signal(SIGUSR1,sigFunc);
        wait(NULL);
        exit(0);
    }

    close(exitPipe[1]);     // 子进程接收任务并分配给子线程

    threadPool_t threadPool;//这个数据结构里面包含了线程池运行的所有组件
    threadPool.tidArr = (pthread_t *)calloc(workerNum,sizeof(pthread_t));
    threadPool.workerNum = workerNum;
    pthread_mutex_init(&threadPool.mutex,NULL);
    pthread_cond_init(&threadPool.cond,NULL);
    threadPool.exitflag = 0; //一开始是不需要退出的

    bzero(&threadPool.taskQueue,sizeof(queue_t));
    makeWorker(&threadPool);

    int sockfd;
    tcpInit(&sockfd, ip, port);

    int epfd = epoll_create(1);
    epollAdd(epfd,sockfd);
    epollAdd(epfd,exitPipe[0]);

    while(1){
        struct epoll_event readySet[2];
        int readyNum = epoll_wait(epfd,readySet,2,-1);

        for(int i = 0; i < readyNum; ++i){
            if(readySet[i].data.fd == sockfd){
                int netfd = accept(sockfd,NULL,NULL);

                pthread_mutex_lock(&threadPool.mutex);
                Enqueue(&threadPool.taskQueue,netfd);
                printf("master send a task!\n");
                pthread_cond_signal(&threadPool.cond);
                pthread_mutex_unlock(&threadPool.mutex);
            }
            else if(readySet[i].data.fd == exitPipe[0]){
                printf("threadPool is going to exit!\n");
                pthread_mutex_lock(&threadPool.mutex);
                threadPool.exitflag = 1;
                pthread_cond_broadcast(&threadPool.cond);
                pthread_mutex_unlock(&threadPool.mutex);
                //for(int j = 0; j < workerNum; ++j){
                //    pthread_cancel(threadPool.tidArr[j]);
                //}

                for(int j = 0; j < workerNum; ++j){
                    pthread_join(threadPool.tidArr[j],NULL);
                }
                printf("all worker is exited!\n");
                pthread_exit(NULL);
            }
        }
    }
    return 0;
}

